package com.gylang.sso.service.impl;

import com.gylang.common.jwt.JwtRole;
import com.gylang.common.jwt.JwtUserDetails;
import com.gylang.sso.domain.SysMenu;
import com.gylang.sso.domain.SysUser;
import com.gylang.sso.repository.SysUserRepository;
import com.gylang.sso.service.SysMenuService;
import com.gylang.sso.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author gylang,
 * @data 2019/11/16 9:37,
 * @DESC
 */
@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserRepository sysUserRepository;

    @Autowired
    private SysMenuService sysMenuService;

    @Override
    public SysUser findByUserName(String userName) {
        return sysUserRepository.findByName(userName);
    }

    @Override
    public Set<String> findPermissions(String username) {
        Set<String> perms = new HashSet<>();
        List<SysMenu> sysMenus = sysMenuService.findByUsername(username);
        for (SysMenu sysMenu : sysMenus) {
            if (sysMenu.getPerms() != null && !"".equals(sysMenu.getPerms())) {
                perms.add(sysMenu.getPerms());
            }
        }
        return perms;
    }

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        System.out.println("用户名" + s);
        SysUser user = sysUserRepository.findByName(s);
        Set<String> permissions = findPermissions(s);
        System.out.println(permissions);
        JwtUserDetails userDetails = new JwtUserDetails(user.getId(), user.getName(), user.getPassword(), user.getSalt(), new ArrayList<>(permissions));
        return userDetails;
    }
}
